from pathlib import Path
from decouple import config
from datetime import timedelta
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = config('SECRET_KEY')

BUCKET_NAME=config('BACKET_NAME')
QINIU_AK=config('QINIU_AK')
QINIU_SK=config('QINIU_SK')
QINIU_DOMAIN=config('QINIU_DOMAIN')
IMAGE_STYLE={
        'homeView': '?imageView2/2/w/300/h/400',  # 首页展示图参数
        'thumbnail': '?imageView2/2/w/220/h/220',  # 缩略图参数
        'large': '?imageView2/2/w/790'           # 放大图参数
    }
#'django-insecure-j3@_v(1#$pjkw^s&u2xp*b)^1!*b+4_%*8m8g71r98rmhx68ty'

# SECURITY WARNING: don't run with debug turned on in production!

#EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'sandbox.smtp.mailtrap.io'  # Mailtrap 的测试服务器
EMAIL_PORT = 2525  # Mailtrap 默认端口
EMAIL_HOST_USER =config('EMAIL_HOST_USER')
EMAIL_HOST_PASSWORD =config('EMAIL_HOST_PASSWORD')
#EMAIL_USE_TLS = True  # 启用 TLS 加密
DEFAULT_FROM_EMAIL = 'tests@mailtrap.io'  # 虚拟发件人地址（可任意填写）

DEBUG = True

ALLOWED_HOSTS = []
CSRF_TRUSTED_ORIGINS = [
    "http://localhost:5173",
    "http://127.0.0.1:5173",
    "http://127.0.0.1:8000"
]


# Application definition

INSTALLED_APPS = [
    'simpleui',
     'drf_yasg',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'users.apps.UsersConfig',
    'products.apps.ProductsConfig',
    'orders.apps.OrdersConfig',
    'corsheaders',
]

# 在MIDDLEWARE中添加（注意顺序，要尽量靠前）
MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',  # 这个要放在最前面
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
SIMPLEUI_HOME_INFO = False
# SIMPLEUI_LOGIN_PARTICLES = False
ROOT_URLCONF = 'backend.urls'
# DRF 配置
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.AllowAny',
    ],
    'DEFAULT_THROTTLE_RATES': {
        'send_code': '5/min',
        'login': '10/min',
        'ips': '60/min',
    },
    'DEFAULT_FILTER_BACKENDS': [
        'django_filters.rest_framework.DjangoFilterBackend',
    ],
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 30,
    'MAX_PAGE_SIZE': 50,  # 每页最大数量限制
}


AUTH_USER_MODEL = 'users.CustomUser'  # 替换为您的应用和模型名

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'backend.wsgi.application'


# Database
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases
DATABASES = {
    'default': {
        'ENGINE': 'django_dmPython',  # 使用的数据库后端
        'NAME': 'TRADE',  # 数据库名称
        'USER': config('DB_USER'),  # 数据库用户名
        'PASSWORD': config('DB_PASSWORD'),  # 数据库密码
        'HOST': config('DB_HOST'),  # 数据库主机地址
        'PORT': config('DB_PORT'),  # 数据库端口
        'OPTIONS': {
            'local_code': 1,
            'connection_timeout': 5,
        }
    }
    # 'default': {
    #     'ENGINE': 'django.db.backends.sqlite3',
    #     'NAME': BASE_DIR / 'db.sqlite3',
    # }
}


# Password validation
# https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/4.2/topics/i18n/

LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'

USE_I18N = True

USE_TZ=False


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.2/howto/static-files/

STATIC_URL = 'static/'

# Default primary key field type
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'


# 添加CORS配置
CORS_ALLOWED_ORIGINS = [
    "http://localhost:5173",  # 你的前端地址
    "http://127.0.0.1:5173",  # 也可以添加这个
    "http://127.0.0.1:8080"
]

# 如果需要允许携带cookie
CORS_ALLOW_CREDENTIALS = True


# 缓存配置
CACHES = {
    "default": {
        "BACKEND": "django.core.cache.backends.locmem.LocMemCache",
        "LOCATION": "unique-snowflake",
        "OPTIONS": {
            "MAX_ENTRIES": 10000,  # 限制缓存条目数
            "CULL_FREQUENCY": 4,  # 当达到MAX_ENTRIES时删除1/4旧缓存
        },
        "TIMEOUT": 3600,  # 默认缓存1小时
    }
}

# settings.py
SWAGGER_SETTINGS = {
    'SECURITY_DEFINITIONS': {
        'Bearer': {
            'type': 'apiKey',
            'name': 'Authorization',
            'in': 'header',
            'description': 'JWT 认证（格式: Bearer <token>）'
        }
    },
    'USE_SESSION_AUTH': False  # 禁用默认的 Session 认证
}


# JWT 配置
SIMPLE_JWT = {
    'ACCESS_TOKEN_LIFETIME': timedelta(days=1),  # 访问令牌有效期改为1天
    'REFRESH_TOKEN_LIFETIME': timedelta(days=3),  # 刷新令牌有效期改为3天
    'ROTATE_REFRESH_TOKENS': True,  # 每次刷新时生成新的刷新令牌
    'BLACKLIST_AFTER_ROTATION': True,  # 旧的刷新令牌加入黑名单
    'UPDATE_LAST_LOGIN': True,  # 更新最后登录时间
}